import React, { useState } from 'react';
import { Input, Button, message, Spin } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { WarehouseItem } from '../types/warehouse';
import ItemsDetail from './ItemsDetail';

// 导入auth服务
import authService from '../services/api/auth';

// 搜索结果接口
export interface SearchResultInfo {
  found: boolean;
  item?: WarehouseItem;
  shelfId?: string;
  layerId?: string;
  positionId?: string;
  warehouseId?: string;
  locationInfo?: string;
}

interface SearchProps {
  warehouseId: string;
  onSearchResult?: (result: SearchResultInfo) => void;
}

const Search: React.FC<SearchProps> = ({ warehouseId, onSearchResult }) => {
  const [searchValue, setSearchValue] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [searchResult, setSearchResult] = useState<SearchResultInfo | null>(null);

  // 使用searchCardCode方法搜索物品
  const searchItemByCardCode = async (cardCode: string): Promise<SearchResultInfo> => {
    try {
      console.log('步骤1: 开始搜索卡片编码:', cardCode);

      // 第一步：通过卡片编码搜索方法获取物品信息
      const apiResult = await authService.searchCardCode(cardCode);
      console.log('步骤1: 卡片编码搜索API返回结果:', apiResult);

      // 检查API返回数据的结构
      let dataArray: any[] = [];

      if (apiResult.success) {
        if (Array.isArray(apiResult.data)) {
          dataArray = apiResult.data;
        } else if (apiResult.data && typeof apiResult.data === 'object' && 'items' in apiResult.data && Array.isArray(apiResult.data.items)) {
          dataArray = apiResult.data.items;
        } else if (apiResult.data && typeof apiResult.data === 'object' && 'data' in apiResult.data && Array.isArray(apiResult.data.data)) {
          dataArray = apiResult.data.data;
        } else if (apiResult.data && typeof apiResult.data === 'object' && !Array.isArray(apiResult.data)) {
          dataArray = [apiResult.data];
        }
      }

      if (dataArray.length > 0) {
        // 获取物品数据
        const cardData = dataArray[0];
        console.log('步骤1: 物品数据:', cardData);
        console.log('步骤1: 物品所有属性名:', Object.keys(cardData));

        // 查找 T736603052777414658 属性，获取库位信息
        let locationInfo = '';
        let originalLocationInfo = ''; // 保存原始的库位信息

        // 尝试直接获取 T736603052777414658 属性
        if (cardData.T736603052777414658) {
          // 从 T736603052777414658 属性获取库位信息
          originalLocationInfo = cardData.T736603052777414658.toString();
          locationInfo = originalLocationInfo;
          console.log('步骤1: 获取到库位信息:', locationInfo);
        } else {
          // 如果找不到精确的属性名，尝试查找包含相关数字的属性
          console.log('步骤1: 未找到 T736603052777414658 属性，搜索其他可能的属性名');

          for (const key of Object.keys(cardData)) {
            if (key.includes('736603052777414658')) {
              originalLocationInfo = cardData[key].toString();
              locationInfo = originalLocationInfo;
              console.log(`步骤1: 找到匹配属性 ${key}:`, locationInfo);
              break;
            }
          }
        }

        // 库位信息变量
        let warehouseName = '';
        let shelfId = '';
        let layerId = '';
        let positionId = '';
        let warehouseId = '';
        let locationCode = ''; // 存储转换后的库位编号

        // 解析库位信息，例如："二号仓库/F1/库位 1_1" 或 "一号仓库/D11/库位1-3" 或 "一号仓库/D11/库位13"
        if (locationInfo) {
          try {
            console.log('步骤2: 开始解析库位信息:', locationInfo);

            // 尝试匹配带分隔符的情况
            let match = locationInfo.match(/([一二]号仓库)\/([A-Z]\d+)\/库位\s*(\d+)[_\-](\d+)/);

            // 如果上面的正则表达式没有匹配，尝试匹配没有分隔符的情况
            if (!match) {
              match = locationInfo.match(/([一二]号仓库)\/([A-Z]\d+)\/库位\s*(\d)(\d)/);
            }

            if (match) {
              const [, warehouse, shelf, layer, position] = match;
              console.log('步骤2: 解析库位信息成功:', { warehouse, shelf, layer, position });

              // 确定仓库ID
              warehouseId = warehouse === "一号仓库" ? "warehouse1" : "warehouse2";
              warehouseName = warehouse;

              // 构建货架ID (如 "F1")
              shelfId = shelf;

              // 构建层ID和位置ID
              layerId = `${shelfId}-L${layer}`;
              positionId = `${layerId}-P${position}`;

              console.log('步骤2: 构建库位ID成功:', {
                warehouseId, warehouseName, shelfId, layerId, positionId
              });

              // 构建库位编号
              const area = shelfId.charAt(0); // 例如：F1 -> F
              const shelfNum = shelfId.substring(1).padStart(3, '0'); // 例如：F1 -> 001
              locationCode = `${area}Q_HJ_${shelfNum}_${layer}_${position}`;

              console.log('步骤2: 构建库位编号:', locationCode);
            } else {
              console.log('步骤2: 无法解析库位信息格式:', locationInfo);
            }
          } catch (error) {
            console.error('步骤2: 解析库位信息出错:', error);
          }
        } else {
          console.log('步骤1: 未找到库位信息');
        }

        // 从返回的数据中提取物品信息，按照特定字段映射
        // name: 物品名称
        // T527635558076391424: 取得日期
        // T527635705355182080: 卡片编码
        // T527635710128300032: 物品名称（新增）
        const item: WarehouseItem = {
          id: cardData.id || cardData._id || cardData.thingId || '',
          name: cardData.T527635710128300032 || cardData.name || cardData.thingName || '未命名物品', // 优先使用T527635710128300032字段作为物品名称
          shelfId: shelfId,
          layerId: layerId,
          positionId: positionId,
          quantity: cardData.quantity || 1,
          sku: cardData.T527635705355182080 || cardData.cardCode || cardCode, // 卡片编码
          category: cardData.category || cardData.type || cardData.thingType || '未分类',
          status: cardData.status || 'normal',
          expiryDate: cardData.T527635558076391424 || cardData.acquireDate || '', // 取得日期
          realLocationId: locationCode || originalLocationInfo, // 优先使用转换后的库位编号
          locationCode: locationCode // 添加库位编号
        };

        console.log('最终构建的物品数据:', item);

        const searchResult = {
          found: true,
          item: item,
          shelfId: item.shelfId,
          layerId: item.layerId,
          positionId: item.positionId,
          warehouseId: warehouseId || warehouseId,
          locationInfo: locationCode || originalLocationInfo // 优先使用转换后的标准库位编号格式
        };

        console.log('最终返回的搜索结果:', searchResult);
        return searchResult;
      } else {
        console.log('步骤1: API返回成功但无数据或数据格式不符合预期');
        if (apiResult.success) {
          console.log('步骤1: API返回数据结构:', apiResult.data);
        }
      }

      return { found: false };
    } catch (error) {
      console.error('搜索过程中发生错误:', error);
      return { found: false };
    }
  };

  const handleSearch = async () => {
    if (!searchValue.trim()) {
      message.warning('请输入卡片编码');
      return;
    }

    setLoading(true);
    try {
      console.log('开始搜索卡片编码:', searchValue.trim());
      const result = await searchItemByCardCode(searchValue.trim());
      console.log('搜索结果:', result);
      setSearchResult(result);

      // 调用父组件的回调函数传递搜索结果
      if (onSearchResult) {
        console.log('调用父组件回调');
        onSearchResult(result);
      }

      if (!result.found) {
        message.info(`未找到编码为 "${searchValue}" 的物品`);
      } else {
        // 显示更详细的成功信息
        let locationDesc = '';

        // 如果有库位信息，添加到成功消息中
        if (result.locationInfo) {
          try {
            // 尝试解析标准库位编号格式，如 "AQ_HJ_001_1_1"
            const parts = result.locationInfo.split('_');
            if (parts.length >= 5) {
              const area = parts[0].charAt(0); // 如 "A"
              const shelfNum = parseInt(parts[2], 10) || 1; // 如 "001" -> 1
              const layer = parts[3]; // 如 "1"
              const position = parts[4]; // 如 "1"

              // 确定仓库名称
              let warehouseName = '';
              if (['A', 'B', 'C', 'D'].includes(area)) {
                warehouseName = '公物仓一';
              } else if (['E', 'F'].includes(area)) {
                warehouseName = '公物仓二';
              }

              locationDesc = `，位置: ${warehouseName} ${area}${shelfNum}货架 第${layer}层 ${position}号库位`;
            } else {
              // 如果不是标准格式，直接显示
              locationDesc = `，位置: ${result.locationInfo}`;
            }
          } catch (error) {
            console.error('解析库位信息出错:', error);
            locationDesc = `，位置: ${result.locationInfo}`;
          }
        } else if (result.shelfId) {
          // 如果没有库位信息但有货架ID，使用货架ID
          locationDesc = `，位置: ${result.shelfId}`;
        }

        message.success(`已找到物品: ${result.item?.name || '未命名'}${locationDesc}`);
        console.log('搜索成功, 结果:', result);
      }
    } catch (error) {
      console.error('搜索出错:', error);
      message.error('搜索过程中发生错误，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 添加调试渲染函数，检查结果是否正确传递给ItemsDetail
  console.log('当前渲染状态 - searchResult:', searchResult);

  return (
    <div className="warehouse-search tech-card" style={{
      height: '100%',
      display: 'flex',
      flexDirection: 'column',
      width: '100%',
      maxWidth: '100%',
      overflow: 'hidden',
      background: 'linear-gradient(135deg, rgba(0, 21, 41, 0.85), rgba(0, 40, 77, 0.95))',
      padding: '0 0 30px 0' // 底部添加一些内边距
    }}>
      <div className="search-header tech-section" style={{
        padding: '20px',
        borderBottom: '1px solid rgba(64, 169, 255, 0.3)'
      }}>
        <div className="search-input-container" style={{ display: 'flex', alignItems: 'center', marginBottom: '0' }}>
          <Input
            placeholder="请输入卡片编码搜索物品"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            onPressEnter={handleSearch}
            style={{
              width: '350px',
              height: '40px',
              borderColor: '#1890ff',
              color: '#000000',
              backgroundColor: '#ffffff',
              boxShadow: '0 0 10px rgba(24, 144, 255, 0.4)',
              display: 'flex',
              alignItems: 'center'
            }}
            disabled={loading}
            className="tech-input"
            autoFocus
            prefix={<SearchOutlined style={{ color: '#40a9ff', fontSize: '16px' }} />}
          />
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
            loading={loading}
            style={{
              marginLeft: '15px',
              height: '40px',
              background: 'linear-gradient(to right, #1890ff, #096dd9)',
              borderColor: '#40a9ff',
              boxShadow: '0 0 15px rgba(24, 144, 255, 0.4)'
            }}
            className="tech-button"
          >
            搜索
          </Button>
        </div>
      </div>

      <div className="search-results" style={{
        flex: '1 1 auto',
        padding: '20px',
        position: 'relative',
        zIndex: 1,
        overflow: 'auto',
        display: 'flex',
        flexDirection: 'column',
        maxHeight: 'calc(100% - 80px)' // 限制最大高度，防止溢出
      }}>
        {loading ? (
          <div className="tech-loading" style={{
            flex: '1',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            textAlign: 'center',
            padding: '40px',
            marginTop: '-30px', // 向上移动一些
            background: 'linear-gradient(135deg, rgba(0, 34, 77, 0.7), rgba(0, 87, 178, 0.5))',
            borderRadius: '4px',
            border: '1px solid rgba(64, 169, 255, 0.3)'
          }}>
            <Spin size="large" tip="搜索中..." />
          </div>
        ) : searchResult ? (
          searchResult.found && searchResult.item ? (
            <div style={{ flex: '1', display: 'flex', flexDirection: 'column', marginTop: '-30px' }}>
              <div className="tech-search-success" style={{
                marginBottom: '15px',
                color: '#40a9ff',
                padding: '12px 15px',
                background: 'linear-gradient(to right, rgba(24, 144, 255, 0.15), rgba(64, 169, 255, 0.05))',
                borderLeft: '3px solid #40a9ff',
                borderRadius: '2px',
                boxShadow: '0 2px 8px rgba(0, 128, 255, 0.15)'
              }}>
                <div style={{ fontWeight: 'bold', fontSize: '16px' }}>搜索成功，显示物品详情：</div>
                <div style={{ marginTop: '5px', fontSize: '13px', color: 'rgba(255, 255, 255, 0.85)' }}>
                  点击顶部"仓库地图"按钮可返回仓库视图
                </div>
              </div>
              <div className="tech-detail-container" style={{
                flex: '1',
                background: 'linear-gradient(135deg, rgba(0, 34, 77, 0.7), rgba(0, 87, 178, 0.5))',
                borderRadius: '4px',
                border: '1px solid rgba(64, 169, 255, 0.3)',
                boxShadow: '0 0 20px rgba(0, 128, 255, 0.2)'
              }}>
                <ItemsDetail
                  warehouseId={searchResult.warehouseId || warehouseId}
                  selectedShelfId={searchResult.shelfId || null}
                  selectedLayerId={searchResult.layerId || null}
                  selectedPositionId={searchResult.positionId || null}
                  searchItem={searchResult.item}
                  locationInfo={searchResult.locationInfo}
                />
              </div>
            </div>
          ) : (
            <div className="tech-empty-container" style={{
              flex: '1',
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
              textAlign: 'center',
              padding: '40px',
              marginTop: '-30px', // 向上移动一些
              background: 'linear-gradient(135deg, rgba(0, 34, 77, 0.7), rgba(0, 87, 178, 0.5))',
              borderRadius: '4px',
              border: '1px solid rgba(64, 169, 255, 0.3)',
              boxShadow: '0 0 15px rgba(0, 128, 255, 0.15)'
            }}>
              <h3 style={{ color: '#ff4d4f', marginBottom: '10px' }}>未找到匹配的物品</h3>
              <p className="tech-text" style={{ color: 'rgba(255, 255, 255, 0.85)' }}>请检查卡片编码是否正确，或尝试其他编码</p>
            </div>
          )
        ) : (
          <div className="tech-welcome" style={{
            flex: '1',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
            textAlign: 'center',
            padding: '60px 20px',
            marginTop: '-30px', // 向上移动一些
            background: 'linear-gradient(135deg, rgba(0, 34, 77, 0.7), rgba(0, 87, 178, 0.5))',
            borderRadius: '4px',
            border: '1px solid rgba(64, 169, 255, 0.3)',
            boxShadow: '0 0 20px rgba(0, 128, 255, 0.2)',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '2px',
              background: 'linear-gradient(90deg, transparent, #40a9ff, transparent)',
              opacity: 0.7
            }}></div>
            <SearchOutlined style={{
              fontSize: '48px',
              color: '#40a9ff',
              marginBottom: '20px',
              opacity: 0.9,
              textShadow: '0 0 20px rgba(24, 144, 255, 0.8)'
            }} />
            <h3 style={{ color: '#fff', marginBottom: '15px', fontSize: '20px', letterSpacing: '1px' }}>物品搜索</h3>
            <p style={{ color: 'rgba(255, 255, 255, 0.85)' }}>请输入卡片编码进行搜索</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Search;
